<template>
  <xh-container
    btnText="保存"
    @onSave="handleClickSubmit"
    :title="formData.id ? '编辑' : '新增'"
  >
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item label="验货日期" name="inspectionTime" required>
          <uni-datetime-picker
            type="date"
            v-model="formData.inspectionTime"
            :start="Date.now()"
          />
        </uni-forms-item>
        <uni-forms-item label="抽验箱号" name="samplingNum" required>
          <uni-easyinput
            v-model="formData.samplingNum"
            placeholder="抽验箱号"
          />
        </uni-forms-item>
        <uni-forms-item label="产品名称" name="productName" required>
          <xh-data-select
            v-model="formData.productName"
            :localdata="productList"
            @change="handleChangeProduct"
          ></xh-data-select>
        </uni-forms-item>
        <uni-forms-item label="柜号" name="orderNum" required>
          <xh-multiple-select
            v-model="formData.orderNum"
            placeholder="请选择柜号"
            :localdata="cabinetNumList"
            @change="handleChangeCabinet"
          />
        </uni-forms-item>
        <uni-forms-item label="流转号" name="lzNum">
          <xh-multiple-select
            v-model="formData.lzNum"
            placeholder="请选择流转号"
            :localdata="lzNumList"
            isSearch
            @onSearch="handleLzSearch"
          />
        </uni-forms-item>
      </uni-forms>
      <xh-button :borderRadius="0" type="default" @click="handelClickSure"
        >确认</xh-button
      >
      <uni-table border stripe emptyText="暂无更多数据">
        <!-- 表头行 
					 版样吊瓶: 裁片编号（下拉选择）、数量、结论
					-->
        <uni-tr>
          <uni-th align="center">流转号</uni-th>
          <uni-th align="center">GX01</uni-th>
          <uni-th align="center">GX02</uni-th>
          <uni-th align="center">GX03</uni-th>
          <uni-th align="center">GX04</uni-th>
          <uni-th align="center">GX05</uni-th>
          <uni-th align="center">GX06</uni-th>
          <uni-th align="center">GX07</uni-th>
          <uni-th align="center">GX08</uni-th>
          <uni-th align="center">GX09</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in lzTableData" :key="index">
          <uni-td align="center">
            {{ item.goboCode }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx01 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx02 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx03 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx04 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx05 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx06 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx07 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx08 }}
          </uni-td>
          <uni-td align="center">
            {{ item.gx09 }}
          </uni-td>
        </uni-tr>
      </uni-table>
      <uni-section title="新增不良项目" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行 
					 版样吊瓶: 裁片编号（下拉选择）、数量、结论
					-->
          <uni-tr>
            <uni-th align="center">不良项目</uni-th>
            <uni-th align="center">项目描述</uni-th>
            <uni-th align="center">状态</uni-th>
            <uni-th align="center">数量</uni-th>
            <uni-th align="center">图片</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>

          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">
              {{ item.badProject }}
            </uni-td>
            <uni-td align="center">
              {{ item.projectDescription }}
            </uni-td>
            <uni-td align="center">
              {{ item.status }}
            </uni-td>
            <uni-td align="center">
              {{ item.num }}
            </uni-td>
            <uni-td align="center">
              <image
                style="width: 50px; height: 50px"
                :src="item.picturePath"
                mode="widthFix"
              >
              </image>
            </uni-td>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="新增不良项目"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item label="不良项目" name="badProject">
            <uni-data-select
              v-model="detailData.badProject"
              :localdata="badProjectList"
              @change="handleBadProject"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="项目描述" name="projectDescription">
            <xh-data-select
              v-model="detailData.projectDescription"
              :localdata="projectDescriptionList"
            />
          </uni-forms-item>
          <uni-forms-item label="状态" name="status">
            <xh-data-select
              v-model="detailData.status"
              :localdata="projectStatusList"
            />
          </uni-forms-item>
          <uni-forms-item label="数量" name="num">
            <uni-easyinput
              type="number"
              v-model="detailData.num"
              placeholder="请输入数量"
            />
          </uni-forms-item>
          <uni-forms-item label="图片" name="picturePath">
            <xh-image
              :src="detailData.picturePath"
              @onSuccess="handleSuccessImg"
            />
          </uni-forms-item>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import { formatSelectList } from "@/utils/business.js";
import {
  addInspectionMng,
  getProductNameList,
  getSelectLZnum,
  getListByMngId,
  updateInspectionMng,
} from "@/api/purchase/inspectionRecords.js";
import { getBadProject } from "@/api/system/dict.js";
import { decodeParams } from "@/utils/common.js";

export default {
  data() {
    return {
      formData: {},
      detailData: {},
      editData: {},
      tableData: [],
      inspectList: [],
      productList: [],
      cabinetNumList: [], // 柜号
      lzNumList: [],
      badProjectList: [], // 不良项目list
      projectDescriptionList: [], // 项目描述list
      lzTableData: [],
      projectStatusList: [
        { text: "轻微", value: "轻微" },
        { text: "严重", value: "严重" },
      ], // 项目描述list
      rules1: {
        inspectionTime: {
          rules: [
            {
              required: true,
              errorMessage: "请选择验货日期",
            },
          ],
        },
        orderNum: {
          rules: [
            {
              required: true,
              errorMessage: "请选择柜号",
            },
          ],
        },
        productName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品名称",
            },
          ],
        },
        samplingNum: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品名称",
            },
          ],
        },
      },
      rules2: {},
    };
  },
  onLoad(options) {
    this.fetchEditData(decodeParams(options));
  },
  computed: {},
  created() {
    this.fetchProductList();
    this.fetchBadProduct();
  },
  mounted() {},
  methods: {
    handleLzSearch(val) {
      const { orderNum } = this.formData;
      getSelectLZnum({ workOrderCodes: orderNum, seq: val }).then((res) => {
        this.lzNumList = formatSelectList(res.data, {
          text: "goboCode",
          value: "goboCode",
        });
      });
    },
    fetchEditData(options) {
      const { id } = options;
      if (id) {
        const { orderNum, ...rest } = options;
        this.formData = {
          ...rest,
          orderNum: orderNum.split(","),
        };
        this.handleChangeCabinet();
        getListByMngId({ id }).then((res) => {
          const { data } = res;
          if (Array.isArray(data)) {
            this.formData = {
              ...this.formData,
              lzNum: data.map((item) => item.goboCode),
            };
            this.lzTableData = data.filter((item) => item.goboCode);
          }
        });
      }
    },
    handelClickSure() {
      if (this.formData.lzNum?.length) {
        const { orderNum, lzNum } = this.formData;
        getSelectLZnum({ workOrderCodes: orderNum, seqs: lzNum }).then(
          (res) => {
            this.lzTableData = res.data;
          }
        );
        this.lzTableData = [];
      } else {
        this.lzTableData = [];
      }
    },
    handleSuccessImg(url) {
      this.detailData = {
        ...this.detailData,
        picturePath: url,
      };
    },
    handleBadProject(val) {
      const arr = this.allBadProjectList.filter(
        (item) => item.dictLabel === val
      );
      this.projectDescriptionList = formatSelectList(arr, {
        text: "dictValue",
        value: "dictValue",
      });
    },
    fetchBadProduct() {
      getBadProject().then((res) => {
        const { data } = res;
        this.allBadProjectList = data;
        const arr = [];
        data.forEach((item) => {
          if (!arr.includes(item.dictLabel)) {
            arr.push(item.dictLabel);
          }
        });
        this.badProjectList = formatSelectList(arr);
      });
    },
    handleChangeCabinet(data) {
      const workOrderCodes = data
        ? data.map((item) => item.value)
        : this.formData.orderNum;
      getSelectLZnum({ workOrderCodes }).then((res) => {
        const { data } = res;
        this.lzNumList = formatSelectList(data, {
          text: "goboCode",
          value: "goboCode",
        });
      });
    },
    fetchProductList() {
      getProductNameList().then((res) => {
        const keys = Object.keys(res);
        this.productResList = res;
        this.productList = formatSelectList(keys);
        if (this.formData.productName) {
          this.handleChangeProduct({ value: this.formData.productName });
        }
      });
    },
    handleChangeProduct(item) {
      const { value } = item;
      this.cabinetNumList = formatSelectList(this.productResList[value]);
    },
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
    },
    // 删除
    handelClickDel(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then((values) => {
          const { orderNum } = values;
          const params = {
            ...this.formData,
            ...values,
            orderNum: orderNum?.join(","),
            badProjectList: [...this.tableData, ...this.lzTableData],
            type: "2",
          };
          if (this.formData.id) {
            updateInspectionMng(params).then(() => {
              this.$modal.msgSuccess("编辑成功！");
              this.clearData();
              this.$nav.navigateBack();
            });
          } else {
            addInspectionMng(params).then(() => {
              this.$modal.msgSuccess("新增成功！");
              this.clearData();
              this.$nav.navigateBack();
            });
          }
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    formatSelectOptions(arr) {
      return arr?.map((item) => ({
        ...item,
        text: item.insCode,
        value: item.insCode,
      }));
    },
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          this.tableData.push(this.detailData);
          this.detailData = {};
          this.$refs.xhPopup.close();
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    // 添加
    handelClickAdd() {
      this.$refs.form1.validate().then(() => {
        this.$refs.xhPopup.open("top");
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}
.img-wrapper {
  height: 60px;
  width: 60px;
  border: 1px solid $uni-border-color;
}
</style>
